﻿using System;
using System.Text;
using System.Web;
using System.IO;

namespace TidyBlog.Util
{
    /// <summary>
    /// 文件上传类
    /// </summary>
    public class FileUploader
    {
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file">上传文件</param>
        /// <param name="path">上传路径</param>
        /// <param name="fileName">文件名</param>
        /// <returns>文件路径</returns>
        public static string Save(HttpPostedFileBase file, string path, string directory, string fileName)
        {
            if (file == null)
            {
                return null;
            }

            string localPath;

            // 保证路径以“/”结尾
            if (!path.EndsWith("/"))
            {
                path += "/";
            }

            if (directory == null)
            {
                // 默认目录
                directory = DateTime.Now.ToString("yyyyMM") + "/";
            }
            else if (directory != String.Empty && !directory.EndsWith("/"))
            {
                // 保证目录以“/”结尾
                directory += "/";
            }
            path += directory;

            localPath = HttpContext.Current.Server.MapPath(path);

            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }

            localPath += fileName;
            file.SaveAs(localPath);

            return path + fileName;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file">上传文件</param>
        /// <param name="path">上传路径</param>
        /// <returns>文件路径</returns>
        public static string Save(HttpPostedFileBase file, string path)
        {
            return Save(file, path, null, GetRandomFilePath(Path.GetExtension(file.FileName)));
        }

        /// <summary>
        /// 获取随机文件名（当前年月日时分秒+五位随机数）
        /// </summary>
        /// <param name="extName">扩展名</param>
        /// <returns>随机文件名</returns>
        public static string GetRandomFilePath(string extName)
        {
            StringBuilder fileName = new StringBuilder(DateTime.Now.ToString("yyyyMMddHHmmss"));

            Random rnd = new Random();
            sbyte i = 5;
            while (--i >= 0)
            {
                fileName.Append(rnd.Next(10));
            }

            if (extName[0] != '.')
            {
                fileName.Append(".");
            }
            fileName.Append(extName);

            return fileName.ToString();
        }
    }
}
